import axios from "axios"
import host from '../../settings'
import { Message } from "element-ui"

async function SendRequestToResourceService(url = '', query = {}, success = () => {
}, fail = () => {
}) {
  try {
    const response = await axios.post(host.RESOURCE_SERVICE_API + url, query, {
      withCredentials: false
    })
    if (response.status === 200) {
      success(response)
      // this.$message.success(response.msg)
      return response.data
    } else {
      fail(response)
      Message.error(response.status.toString())
      console.log(response)
      return undefined
    }
  } catch (err) {
    fail()
    Message.error(err)
    return undefined
  }
}

function checkRewardDataIsLatest(latestIdentifier) {
  const localTypeList = localStorage.getItem('reward_type_list')
  const localRewardList = localStorage.getItem('reward_list')
  if (localTypeList === null) { return false }
  if (localRewardList === null) { return false }
  const localIdentifier = localStorage.getItem('reward_identifier')
  return localIdentifier === latestIdentifier
}

export const universal_reward_api_get = async () => {
  const defaultValue = {
    rewardTypeList: [],
    rewardList: {}
  }

  const rewardIdentifierResponse = await SendRequestToResourceService('/get_reward_identifier', {
    project: 'westgame',
    environment: host.EVN
  })
  if (rewardIdentifierResponse && rewardIdentifierResponse.status === 'success') {
    if (checkRewardDataIsLatest(rewardIdentifierResponse.identifier)) {
      return {
        rewardTypeList: JSON.parse(localStorage.getItem('reward_type_list')),
        rewardList: JSON.parse(localStorage.getItem('reward_list'))
      }
    } else {
      const rewardResponse = await SendRequestToResourceService('/get_reward', {
        project: 'westgame',
        environment: host.EVN
      })
      if (rewardResponse) {
        if (rewardResponse.status === 'success') {
          localStorage.setItem('reward_identifier', rewardResponse.identifier)
          localStorage.setItem('reward_type_list', JSON.stringify(rewardResponse.reward_type_list))
          localStorage.setItem('reward_list', JSON.stringify(rewardResponse.reward_list))
          return {
            rewardTypeList: rewardResponse.reward_type_list,
            rewardList: rewardResponse.reward_list
          }
        } else {
          console.log(rewardResponse)
          Message.error(`获取奖励错误：${rewardResponse.message}`)
        }
      }
    }
  }
  return defaultValue
}
